package com.elookinto.sample;

import java.util.Collection;
import java.util.logging.Logger;
import org.apache.felix.http.api.ExtHttpService;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;

public class Activator implements BundleActivator {
    
    private JerseyServletRegistration jsr;
    private ServiceTracker httpTracker;
    private Logger logger = Logger.getLogger(Activator.class.getName());

    //http://www.knopflerfish.org/osgi_service_tutorial.html
    public void start(final BundleContext bc)   {
        
        logger.info("started my bundle");
        httpTracker = new ServiceTracker(bc, ExtHttpService.class.getName(), null);
        httpTracker.open();
        ServiceListener serviceListener = new ServiceListener() {
            public void serviceChanged(ServiceEvent ev) {
                ServiceReference sr = ev.getServiceReference();
                switch (ev.getType()) {
                    case ServiceEvent.REGISTERED: {
                        ExtHttpService myservice = (ExtHttpService) bc.getService(sr);
                        jsr = new JerseyServletRegistration();
                        jsr.setExtHttpService(myservice);
                        jsr.init();
                    }
                    break;
                    
                    case ServiceEvent.UNREGISTERING: {
                        jsr.destroy();
                    }
                    break;
                }
            }
        };
        
        final String filter = "(objectclass=" + ExtHttpService.class.getName() + ")";
        try {
            bc.addServiceListener(serviceListener, filter);
            final Collection<ServiceReference<ExtHttpService>> srl;
            srl = bc.getServiceReferences(ExtHttpService.class, filter);
            for (ServiceReference<ExtHttpService> se: srl) {
                serviceListener.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, se));
            }
        } catch (InvalidSyntaxException e) {
            logger.severe(e.toString());
        }
    }
    
    public void stop(final BundleContext context) {
        jsr.destroy();
        httpTracker.close();
    }
}
